/*********************************************************************************
  *Copyright(C),2015-2020, TUYA www.tuya.comm
  *FileName:    tuya_ipc_qrcode_demo
**********************************************************************************/
#include "tuya_ipc_qrcode_demo.h"
#include "SdkVideo.h"
#include "InSdkSoundPlay.h"

#define DEF_TAG             "TYQrcode"

#if CMAKE_NONSUPPORT_GET_YUV
Com_s8 g_ComVideo_SubBuff_Flag = 1;
#endif

Com_u8 s_enable_qrcode;

Com_void Set_enable_qrcode(Com_u8 flag)
{
    s_enable_qrcode = flag;
}

INT_T __tuya_linux_get_snap_qrcode(CHAR_T* buf)
{
    //Developers need to parse QR code information from cameras
    //a typical string is {"s":"ssidxxxx","p":"password","t":"token frome tuya cloud"}
    int ret;
    int qrcode_w = SENSOR_SUB_WIDTH;
    int qrcode_h = SENSOR_SUB_HEIGHT;

    ret = get_wifi_qrcode(buf,qrcode_w * qrcode_h,qrcode_w,qrcode_h);
    if(ret == 0)
    {
        return 0;
    }

    return -1;
}

void *thread_qrcode(void *arg)
{
    DEF_COM_SET_THREAD_NAME("Qrcode_Scan",g_ComThread_Num);

    int ret;
    StSdkQrcodeInfo info;

    memset(&info,0,sizeof(info));
    PRT_INFO(DEF_TAG,"Qrcode Thread start\n");
    if(Ext_InComFile_Access(DEF_FLAG_NO_NETWORK) == DEF_COM_FILE_NOT_EXIST)
    {
        goto exit_qrcode;
    }

    s_enable_qrcode = DEF_COM_TRUE;

#if CMAKE_NONSUPPORT_GET_YUV
    g_ComVideo_SubBuff_Flag = 0;
    sleep(1);
#endif

    while(s_enable_qrcode && g_ComThread_Running)
    {
        if((Ext_InComFile_Access(DEF_FLAG_NO_NETWORK) == DEF_COM_FILE_NOT_EXIST) ||
           (Ext_InComFile_Access(DEF_FLAG_NET_CONNECT_OK) == DEF_COM_FILE_EXIST))
        {
            PRT_INFO(DEF_TAG,"device connected network\n");
            break;
        }

        ret = Ext_SdkMediaCom_GetQRCodeData(&info);
        if (ret != 0)
        {
            continue;
        }

        ret = __tuya_linux_get_snap_qrcode((PCHAR_T)info.buf);
        if(ret == 0)
        {
            OPERATE_RET ret = tuya_ipc_direct_connect((PCHAR_T)info.buf,TUYA_IPC_DIRECT_CONNECT_QRCODE);
            if(ret == OPRT_OK)
            {
                Ext_InSdkSpkPlay_WavInit(DEF_WAV_QRCODE);
                PRT_INFO(DEF_TAG,"register to tuya cloud via qrcode success\n");
                Ext_SdkMediaCom_ReleaseQRCodeData();
                break;
            }
        }

        Ext_SdkMediaCom_ReleaseQRCodeData();
    }

#if CMAKE_NONSUPPORT_GET_YUV
    g_ComVideo_SubBuff_Flag = 1;
#endif

exit_qrcode:
    Ext_SdkVideo_Start();
    DEF_COM_EXIT_THREAD(g_ComThread_Num);
}

Com_void Ext_SdkQRcode_Init(Com_void)
{
    pthread_t id;

    pthread_create(&id, NULL, thread_qrcode, NULL);
    pthread_detach(id);
}
